﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using CommonLib;

namespace WordStat.PluginService
{
    internal class PluginService : IPluginHost
    {
        private List<PluginItem> _plugins = new List<PluginItem>();

        public List<PluginItem> PluginItems
        {
            get { return _plugins; }
        }

        public void FindPlugins()
        {
            FindPlugins(AppDomain.CurrentDomain.BaseDirectory);
        }

        private void FindPlugins(string Path)
        {
            _plugins.Clear();

            foreach (var fileOn in Directory.GetFiles(Path, "*.dll"))
            {
                var file = new FileInfo(fileOn);

                if (file.Extension.Equals(".dll"))
                    AddPlugin(fileOn);
            }
        }

        public void ClosePlugins()
        {
            foreach (var pluginOn in _plugins)
                pluginOn.Plugin.Dispose();

            _plugins.Clear();
        }

        private void AddPlugin(string FileName)
        {
            var pluginAssembly = Assembly.LoadFrom(FileName);

            foreach (var pluginType in pluginAssembly.GetTypes())
            {
                if (!pluginType.IsPublic)
                    continue;

                if (pluginType.IsAbstract)
                    continue;

                var typeInterface = pluginType.GetInterface(typeof(IPlugin).FullName, true);

                if (typeInterface == null)
                    continue;

                var newPlugin = new PluginItem { Plugin = (IPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())) };

                newPlugin.Name = newPlugin.Plugin.Name;

                newPlugin.Plugin.Host = this;

                newPlugin.Plugin.Initialize();

                _plugins.Add(newPlugin);

            }
        }

        public void Feedback(string Feedback, IPlugin Plugin) { }

        public IPlugin GetPlugin(string name)
        {
            return (from pluginItem in _plugins where pluginItem.Name == name select pluginItem.Plugin).FirstOrDefault();
        }
    }

    public class PluginItem
    {
        public IPlugin Plugin { get; set; }

        public string Name { get; set; }
    }
}
